import { getViewportOffset } from "@/utils/domUtils"
import { GetanTableProps } from "../types"
import { isNumber, isUndefined } from "@/utils"

/**
 * 自动计算表格最大高度
 */
export function useFlexHeight(tableRef: Ref, props: Ref<Partial<GetanTableProps>>) {
    const deviceHeight = ref(150)
    const flex = computed(() => !isUndefined(unref(props).useFlexHeight))

    async function computeTableHeight() {
        const table = unref(tableRef)
        if (!table) {
            return
        }
        if (!flex.value) {
            return
        }
        const { usePagination, useFlexHeight } = unref(props)
        // @ts-ignore
        const tableEl: any = table?.$el
        const headEl = tableEl.querySelector(".n-data-table-thead")
        const { bottomIncludeBody } = getViewportOffset(headEl)

        const headerH = 60
        let paginationH = 2
        let marginH = 24
        if (usePagination) {
            const paginationEl = tableEl.querySelector(".n-data-table__pagination") as HTMLElement
            if (paginationEl) {
                const offsetHeight = paginationEl.offsetHeight
                paginationH += offsetHeight || 0
            } else {
                paginationH += 28
            }
        }
        let height = bottomIncludeBody - (headerH + paginationH + marginH)
        const maxHeight = isNumber(useFlexHeight) ? (useFlexHeight as number) : undefined
        height = maxHeight && maxHeight < height ? maxHeight : height
        deviceHeight.value = height
    }

    onMounted(() => {
        nextTick(() => {
            computeTableHeight()
        })
    })

    return { deviceHeight, flex }
}
